<template>
  <div class="main">
    <div class="search">
      <el-form :model="searchForm" :inline="true">
        <el-form-item label="手机号:">
          <el-input v-model="searchForm.userName"  placeholder="请输入要查询的手机号"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getDataFromServer">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="u-list">
      <el-table :data="userTableData" style="width: 100%" border stripe :row-class-name="tableRowClassName">
        <!-- <el-table-column prop="_id" label="_id"  /> -->
        <el-table-column prop="userName" label="手机号"  />
        <el-table-column prop="role" label="角色"  width="100"/>
        <el-table-column prop="vipType" label="会员类型" :formatter="formatterVipType"/>
        <el-table-column prop="createTime" label="创建时间" />
        
        <el-table-column label="到期时间" >
          <template #default="scope">
            {{ scope.row.vipExpireDate || '--'}}
          </template>
        </el-table-column>
        <el-table-column label="剩余天数" prop="remainDays">
          <template #default="scope">
            <template v-if="scope.row.vipType ==='date'">
              {{ scope.row.remainDays || '--'}}
            </template>
            <template v-else>
              --
            </template>
          </template>
        </el-table-column>
        <el-table-column prop="remainNum" label="剩余次数">
          <template #default="scope">
            {{ scope.row.remainNum || '--'}}
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="250" >
          <template #default="scope">
            <template v-if="scope.row.role!=='admin'">
              <el-button size="small" @click="addExpireFn(scope.row)" 
                >增加效期</el-button
              >
              <el-button size="small" type="warning" @click="resetPasswordFn(scope.row)"
                >重置密码</el-button
              >
              <el-button
                size="small"
                type="danger"
                @click="deleteUser(scope.row)"
                >删除</el-button
              >
            </template>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog
      v-model="expireDialogVisible"
      title="修改效期"
      width="500"
      @close="closeDialogCallBack"
    >
      <el-form :model="expireUserForm">
        <el-form-item :label="expireUserForm.vipType==='date' ? '增加天数' : '增加次数'" prop="nums" :rules="[
            {
              required: true,
              message: '效期不能为空',
              trigger: 'blur',
            }
          ]">
          <el-input-number v-model="expireUserForm.nums" :min="1"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeDialogCallBack">取消</el-button>
          <el-button type="primary" @click="submitExpireForm">
            提交
          </el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      v-model="resetPasswordDialogVisible"
      title="重置密码"
      width="500"
      @close="closeDialogCallBack"
    >
      <div>重置后的密码跟手机号相同，确定要重置<span style="font-weight:bold;color:#F56C6C">{{currentUser.userName}}</span>的密码吗？</div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeDialogCallBack">取消</el-button>
          <el-button type="primary" @click="submitResetPasswordForm">
            提交
          </el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      v-model="deleteUserDialogVisible"
      title="删除用户"
      width="500"
      @close="closeDialogCallBack"
    >
      <div>确定要删除<span style="font-weight:bold;color:#F56C6C">{{currentUser.userName}}</span>用户吗？</div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeDialogCallBack">取消</el-button>
          <el-button type="primary" @click="submitDeleteUserForm">
            提交
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { reactive, ref, onMounted } from "vue";
import { formatDate,getDaysDiffNow } from "@/utils/tools.js";
import { dayjs } from "element-plus";
import { ElMessage } from "element-plus";
import { getStorage, setStorage } from "@/utils/storage";
import { request } from '@/api/fetch'
const searchFormKey = 'userList/searchForm'
let localSearchForm = getStorage(searchFormKey)


const searchForm = reactive(localSearchForm || {
  userName:''
})

const userTableData = ref([])
const currentUser = ref(null)

const tableRowClassName = ({
  row,
  rowIndex,
}) => {
  let vipExpireDate = row.vipExpireDate
  if (vipExpireDate && new Date(vipExpireDate).getTime() < new Date().getTime()){
   return 'danger-row'
  }
}

const expireDialogVisible = ref(false)
const resetPasswordDialogVisible = ref(false)
const deleteUserDialogVisible = ref(false)
const expireUserForm = reactive({
  vipType: 'date',
  nums: 1,
})





function formatterVipType (row) {
  // date 按时间购买，count按数量购买
  if (row.vipType === 'date' || !row.vipType) {
    return '按时间'
  } else if( row.vipType === 'num' ){
    return '按次数'
  } else if( row.vipType ==='forever'){
    return '永久有效'
  } else if( row.vipType ==='trial'){
    return '试用'
  } else {
    return '未知'
  }
}

function formatterIsDelete (row) {
  if (!row.isDelete || row.isDelete === '0') {
    return '正常'
  } else {
    return '已删除'
  }
}



function addExpireFn (rowData) {
  expireDialogVisible.value = true
  expireUserForm.vipType = rowData.vipType
  currentUser.value = rowData

}
function resetPasswordFn (rowData) {
  resetPasswordDialogVisible.value = true
  currentUser.value = rowData
}
function deleteUser (rowData) {
  deleteUserDialogVisible.value = true
  currentUser.value = rowData
}

async function getDataFromServer () {
  setStorage(searchFormKey,searchForm)
  let userList = await request('/member/getMemberList',{
    query: {
      userName: searchForm.userName
    }
  })
  userList.forEach(item => {
    item.createTime = formatDate(item.createTime,'YYYY-MM-DD')
    
    if(item.vipType === 'date'){
      item.vipExpireDate = formatDate(item.vipExpireDate,'YYYY-MM-DD')
      item.remainDays = getDaysDiffNow(item.vipExpireDate)
    }
  })
  let adminUserList = userList.filter(item => item.role === 'admin')
  let vipUserList = userList.filter(item => item.role === 'vip')
  
  vipUserList.sort((item, next) => {
    if (item.remainDays) {
      return item.remainDays > next.remainDays ? -1 : 1  
    } else {
      return item.remainNum > next.remainNum ? -1 : 1
    }
  })
  userTableData.value = [...adminUserList,...vipUserList]
  // console.log('userTableData.value:',userTableData.value)
}

function closeDialogCallBack () {
  // console.log('closeDialogCallBack')
  expireDialogVisible.value = false
  resetPasswordDialogVisible.value = false
  deleteUserDialogVisible.value = false
}

async function submitExpireForm () {
  if (!Number.isInteger(expireUserForm.nums) || expireUserForm.nums < 0) {
    ElMessage({
      type: 'error',
      message:'效期必须为正整数'
    })
    return 
  }
  if (!currentUser.value) {
      ElMessage({
      type: 'error',
      message:'用户不能为空'
    })
    return 
  }
  let reqData = {
    id: currentUser.value._id,
    vipType: expireUserForm.vipType,
  }
  // 计算效期增加值
  if (expireUserForm.vipType === 'date') {
    // 增加日期
    // 已过期,就在今天的基础上新增
    let newExpireDate = null
    if (currentUser.value.remainDays < 0) {
      newExpireDate = dayjs().add(expireUserForm.nums, 'day')
    } else {
      // 未过期，就在之前的基础上新增
      newExpireDate = dayjs(currentUser.value.vipExpireDate).add(expireUserForm.nums, 'day')
    }
    reqData['vipExpireDate'] = newExpireDate.format()
  } else {
    // 增加次数
    let newCount = currentUser.value.remainNum + expireUserForm.nums

    reqData['remainNum'] = newCount
  }
  closeDialogCallBack()
  try{
    await request('/member/updateMemberExpire',{
      method:'POST',
      body:reqData
    })
    ElMessage({
      type: 'success',
      message:'更新成功'
    })
    getDataFromServer()
  } catch (error) {
    console.log('error:', error)
    ElMessage({
      type: 'error',
      message:'更新失败'
    })
  }
  
  
}

async function submitResetPasswordForm () {
   // 验证手机号
  if (!currentUser.value) {
    ElMessage({
      type: 'error',
      message:'用户不能为空'
    })
    return
  }
  if (currentUser.role==='admin') {
    ElMessage({
      type: 'error',
      message:'管理员密码不能重置'
    })
    return
  }

  try {
    let res = await request('/member/resetMemberPassword', {
      method:'POST',
      body:{
        id: currentUser.value._id,
        userName: currentUser.value.userName
      }
    })
    console.log('res:', res)
    ElMessage({
      type: 'success',
      message:'重置成功'
    })
  } catch (error) {
    console.log('error:', error)
   
  }

  closeDialogCallBack()
}
async function submitDeleteUserForm () {
  if (!currentUser.value) {
    ElMessage({
      type: 'error',
      message:'用户不能为空'
    })
    return
  }

   try {
    
    let res = await request('/member/deleteMember', {
      method:'POST',
      body:{
        id: currentUser.value._id,
      }
    })
     console.log('res:', res)
    getDataFromServer()
    ElMessage({
      type: 'success',
      message:'删除成功'
    })
  } catch (error) {
    console.log('error:', error)
    ElMessage({
      type: 'error',
      message:'删除失败'
    })
  }

  closeDialogCallBack()
}
onMounted(() => {
  getDataFromServer()
})
</script>
<style lang="scss" scoped>
.main{
  background:white;
  padding:20px;
  .search{
    padding-top: 20px;
    width:100%;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    // border-bottom:1px dashed #eee;
  }
  .u-list{
    margin-top: 20px;
    min-height: calc(100vh - 200px);
  }
}
</style>